package com.avic.controller;

import com.avic.common.constant.SystemLogConstant;
import com.avic.common.constant.UserConstant;
import com.avic.common.convertor.InformationReportConvertor;
import com.avic.common.util.AssertUtil;
import com.avic.common.util.FileUploadUtil;
import com.avic.common.util.ex.BizErrorCode;
import com.avic.common.util.ex.BizException;
import com.avic.common.util.lang.BaseResponse;
import com.avic.common.util.lang.ServiceCallBack;
import com.avic.controller.request.CreateInformationReportReq;
import com.avic.controller.request.GetInformationReportListReq;
import com.avic.controller.request.UpdateInformationReportReq;
import com.avic.controller.result.BaseCreateResourceRes;
import com.avic.controller.result.GetInformationReportListRes;
import com.avic.controller.result.GetInformationReportRes;
import com.avic.controller.result.UploadImageRes;
import com.avic.dal.condition.InformationReportListCondition;
import com.avic.dal.model.InformationReport;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.*;
import java.io.InputStream;
import java.util.List;


@Slf4j
@RestController
@RequestMapping("information/report")
@Api(tags = "信息报告", description = "信息报告")
public class InformationReportController extends AbstractFacadeImpl {

    @ApiOperation(value = "分页查询信息报告列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "requestBody", required = true, dataType = "GetInformationReportListReq")
    })
    @PostMapping("list")
    public GetInformationReportListRes getInformationReportList(@RequestBody GetInformationReportListReq requestBody) {
        final GetInformationReportListRes result = new GetInformationReportListRes();
        return serviceExecuteTemplate.executeService(result, new ServiceCallBack() {
            @Override
            public void check() throws Exception {
            }

            @Override
            public void doService() throws Exception {
                InformationReportListCondition informationReportListCondition = new InformationReportListCondition(
                        requestBody.getCurrentPage(), requestBody.getPageSize()
                );
                informationReportListCondition.setCreateUserName(requestBody.getCreateUserName());
                informationReportListCondition.setReportType(requestBody.getResourceType());

                List<InformationReport> informationReports = informationReportService.informationReportList(informationReportListCondition);

                result.setItemList(InformationReportConvertor.informationReportsToInformationReportInfo(informationReports));
                result.setItemTotal(informationReportService.informationReportListCount(informationReportListCondition));
                result.setSuccess(true);
            }
        });
    }

    @ApiOperation(value = "创建信息报告")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "createInformationReportReq", required = true, dataType = "CreateInformationReportReq"),
            @ApiImplicitParam(name = "current-user-id", paramType = "header", value = "由网关转换放入请求头中，可以不用填写")
    })
    @PostMapping
    public BaseCreateResourceRes createInformationReport(@RequestHeader(value = UserConstant.HEADER_CURRENT_USER_ID_KEY, required = false) String currentUserId,
                                                         @RequestBody CreateInformationReportReq createInformationReportReq) {
        final BaseCreateResourceRes result = new BaseCreateResourceRes();
        return serviceExecuteTemplate.executeService(result, new ServiceCallBack() {
            @Override
            public void check() throws Exception {
                AssertUtil.isNotBlank(currentUserId, "创建人不能为空");
                AssertUtil.isNotBlank(createInformationReportReq.getReportNumber(), "资源编号不能为空");
                AssertUtil.isTrue(informationReportService.informationReportNumberCount(
                        createInformationReportReq.getReportNumber()) <= 0, BizErrorCode.PARAM_ERROR, "资源编号已经存在");

            }

            @Override
            public void doService() throws Exception {
                InformationReport informationReport = new InformationReport();
                informationReport.setCreateUserId(currentUserId);
                informationReport.setReportContext(createInformationReportReq.getReportContext());
                informationReport.setReportName(createInformationReportReq.getReportName());
                informationReport.setReportNumber(createInformationReportReq.getReportNumber());
                informationReport.setReportType(createInformationReportReq.getReportType());
                result.setItemId(informationReportService.createInformationReport(informationReport));

                // 新建系统日志
                systemServiceFeignService.createSystemLog(
                        String.format(SystemLogConstant.CREATE_INFORMATION_REPORT, result.getItemId(),
                                objectMapper.writeValueAsString(createInformationReportReq)), currentUserId);
                result.setSuccess(true);
            }
        });
    }

    @ApiOperation(value = "通过ID获取报告详情")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "reportId", value = "资源ID", required = true, dataType = "path")
    })
    @GetMapping("/{reportId}")
    public GetInformationReportRes getInformationReportRes(@PathVariable("reportId") String reportId) {
        final GetInformationReportRes result = new GetInformationReportRes();
        return serviceExecuteTemplate.executeService(result, new ServiceCallBack() {
            @Override
            public void check() throws Exception {
                AssertUtil.isNotBlank(reportId, "资源编号不能为空");
            }

            @Override
            public void doService() throws Exception {
                result.setInformationReportInfo(InformationReportConvertor.informationReportToInformationReportInfo(
                        informationReportService.getInformationReportById(reportId)));
                result.setSuccess(true);
            }
        });
    }


    @ApiOperation(value = "修改信息报告")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "requestBody", required = true, dataType = "UpdateInformationReportReq")
    })
    @PutMapping
    public BaseResponse updateInformationReport(@RequestBody UpdateInformationReportReq requestBody,
                                                @RequestHeader(value = UserConstant.HEADER_CURRENT_USER_ID_KEY, required = false) String currentUserId) {
        final BaseResponse result = new BaseResponse();
        return serviceExecuteTemplate.executeService(result, new ServiceCallBack() {
            @Override
            public void check() throws Exception {
                AssertUtil.isNotBlank(requestBody.getId(), "ID 不能为空");
                AssertUtil.isNotBlank(requestBody.getReportNumber(), "编号不能为空");

            }

            @Override
            public void doService() throws Exception {

                InformationReport informationReport = informationReportService.getInformationReportById(requestBody.getId());
                AssertUtil.isTrue(null != informationReport, BizErrorCode.PARAM_ERROR, "资源数据不存在");
                if (!StringUtils.equals(informationReport.getReportNumber(), requestBody.getReportNumber())) {
                    AssertUtil.isTrue(informationReportService.informationReportNumberCount(
                            requestBody.getReportNumber()) <= 0, BizErrorCode.PARAM_ERROR, "资源编号已经存在");
                }
                InformationReport informationReportDB = new InformationReport();
                informationReportDB.setReportType(requestBody.getReportType());
                informationReportDB.setReportNumber(requestBody.getReportNumber());
                informationReportDB.setReportName(requestBody.getReportName());
                informationReportDB.setReportContext(requestBody.getReportContext());
                informationReportDB.setId(requestBody.getId());

                informationReportService.updateInformationReport(informationReportDB);

                // 新建系统日志
                systemServiceFeignService.createSystemLog(
                        String.format(SystemLogConstant.UPDATE_INFORMATION_REPORT, informationReportDB.getId(),
                                objectMapper.writeValueAsString(requestBody)), currentUserId);

                result.setSuccess(true);
            }
        });
    }

    @ApiOperation(value = "删除资源报告")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "itemId", paramType = "path", value = "资源ID", required = true)
    })
    @DeleteMapping("/{itemId}")
    public BaseResponse deleteInformationReport(@PathVariable("itemId") String itemId,
                                                @RequestHeader(value = UserConstant.HEADER_CURRENT_USER_ID_KEY, required = false) String currentUserId) {
        final BaseResponse result = new BaseResponse();
        return serviceExecuteTemplate.executeService(result, new ServiceCallBack() {
            @Override
            public void check() throws Exception {
                AssertUtil.isNotBlank(itemId, "资源ID不能为空");

            }

            @Override
            public void doService() throws Exception {

                informationReportService.deleteInformationReport(itemId);

                // 新建系统日志
                systemServiceFeignService.createSystemLog(
                        String.format(SystemLogConstant.DELETE_INFORMATION_REPORT, itemId), currentUserId);
                result.setSuccess(true);
            }
        });
    }

    @ApiOperation(value = "富文本上传文件")
    @PostMapping("/upload")
    public UploadImageRes uploadImage(@RequestParam("multipartFile") MultipartFile multipartFile) {
        final UploadImageRes result = new UploadImageRes();
        return serviceExecuteTemplate.executeService(result, new ServiceCallBack() {
            @Override
            public void check() throws Exception {
                InputStream inputStream = multipartFile.getInputStream();
                AssertUtil.isTrue(multipartFile.getInputStream() != null,
                        BizErrorCode.PARAM_ERROR, "上传的文件不是一个图片");
                Image img = null;
                try {
                    img = ImageIO.read(inputStream);
                } catch (Exception e) {
                    log.error("校验上传文件是否为图片时时，发生异常 {}", e.getMessage());
                    throw new BizException(BizErrorCode.PARAM_ERROR, "上传的文件不是一个图片");
                }
                AssertUtil.isTrue(!(img == null || img.getWidth(null) <= 0 || img.getHeight(null) <= 0),
                        BizErrorCode.PARAM_ERROR, "上传的文件不是一个图片");
            }

            @Override
            public void doService() throws Exception {

                String imagePath = fileUploadUtil.writeUploadFile(multipartFile, FileUploadUtil.UEDITOR_MODULE);
                log.info("文件名：{}", imagePath);
                result.setImagePath(imagePath);
                result.setSuccess(true);
            }
        });
    }
}
